import optparse

class MyOptionParser(optparse.OptionParser):
    def exit(self, status=0, msg=None):
        """
        This is an overwrire of the exit in optparse class,
        in order to handle errors without calling sys.exit
        """
        if msg:
            sys.stderr.write(msg)
        return

    def error(self, msg):
        """
        error(msg : string)

        Print a usage message incorporating 'msg' to stderr and exit.
        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        """
        #self.print_usage(sys.stderr)
        self.exit(2, "Error: %s\n" % msg)

   
    def parse_args(self, args=None, values=None):
        rargs = self._get_args(args)
        if values is None:
            values = self.get_default_values()

        # Store the halves of the argument list as attributes for the
        # convenience of callbacks:
        #   rargs
        #     the rest of the command-line (the "r" stands for
        #     "remaining" or "right-hand")
        #   largs
        #     the leftover arguments -- ie. what's left after removing
        #     options and their arguments (the "l" stands for "leftover"
        #     or "left-hand")
        self.rargs = rargs
        self.largs = largs = []
        self.values = values


        try:
            stop = self._process_args(largs, rargs, values)
        except UnboundLocalError:
            raise NameError('Parsing failed')
        except AttributeError:
            raise NameError('Parsing failed')
        except (optparse.OptionValueError, optparse.BadOptionError), err:
            #print 'parse_args found some error'
            self.error(err.msg)
            raise NameError('Parsing failed')
        
        args = largs + rargs

        return self.check_values(values, args)
